<?php

namespace App\Libs\Common;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 *   接收通知控制器
 */
class ReceiveController extends Controller
{

    private $aop = null;
    private $rsaPublicKeyFilePath = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAl7xewI9b4pyolPxd3Bqyvk2iNSH4fHZPvh4x7gkiWjp54HEHdCEJagqoKlDYDgoBlshx9GsrwAR/01nQOQRq1cS5nTPZJm3e1XubK8DfPOVymD50uoQZtkdQf8my06xoTNaL5luw7jRr7nQPrOrIFb6O0qJg+GJD+drS7Qt58KDMddNq2PZuHeznjnfrbzpCnIJiRKRv/axwE5VkIoZvNDHl+LpykSkW9HcGWRwOb29EDn8OycYAqy6LadEw19pEf9ww+EXEdmV0QRD3QvsAl/Yn304uUSlv9oCOs7oFbfNhC+fZN6PdmkRrNpB2WI7hdP8cT4oabeTgjSjN1xmDdwIDAQAB';

    public $rsaPrivateKey = 'MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCXvF7Aj1vinKiU/F3cGrK+TaI1Ifh8dk++HjHuCSJaOnngcQd0IQlqCqgqUNgOCgGWyHH0ayvABH/TWdA5BGrVxLmdM9kmbd7Ve5srwN885XKYPnS6hBm2R1B/ybLTrGhM1ovmW7DuNGvudA+s6sgVvo7SomD4YkP52tLtC3nwoMx102rY9m4d7OeOd+tvOkKcgmJEpG/9rHATlWQihm80MeX4unKRKRb0dwZZHA5vb0QOfw7JxgCrLotp0TDX2kR/3DD4RcR2ZXRBEPdC+wCX9iffTi5RKW/2gI6zugVt82EL59k3o92aRGs2kHZYjuF0/xxPihpt5OCNKM3XGYN3AgMBAAECggEAXsOUYaqm9jZkyvd6HxbFfzi5D3nx2LmDP/dXs5Qc0kEnENdGkm53lLSnJhZreQkiyOrS0JWGM1wcAQFcm994YZ2FVvqkqe2Ad8/Er2S7hyq9kPugp0QNUtvjGIv9lVldom9z3CBztbE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_initialize()
    {
        header("Content-type: text/html; charset=utf-8");
        vendor("alipay-sdk.aop.AopClient");

        if (is_null($this->aop)) {
            $this->aop = new \AopClient();
        }
    }


    /**
     * 支付宝小程序异步地址
     * @return
     */
    public function ali_notify()
    {
        $request = I();

        $charset = 'utf8';
        $sign_type = 'RSA2';

        $log['notify_type'] = $request['notify_type'];
        $log['out_order_no'] = $request['out_order_no'];
        $log['zm_order_no'] = $request['zm_order_no'];
        $log['out_trans_no'] = $request['out_trans_no'];
        $log['log'] = json_encode($request);
        $log['create_time'] = date("Y-m-d H:i:s");
        $alipay_fund_order_no = $request['alipay_fund_order_no'];//资金流水号，用于商户与支付宝进行对账

        $checkSign = $this->aop->rsaCheckV1($request, $this->rsaPublicKeyFilePath, $sign_type);

        if (!$checkSign) {
            file_put_contents(time() . '.txt', "小程序异步通知验签失败,外部单号：" . $request['out_order_no']);
        }

        $res = false;

        //小程序创建订单后异步通知
        if ($request['notify_type'] == 'ZM_RENT_ORDER_CREATE') {
            $res = $this->createOrder_notify($request);

            if ($res) $log['keyword'] = '小程序订单创建成功';
        }

        //订单扣款(包括分期付)
        if ($request['notify_type'] == 'ZM_RENT_ORDER_FINISH') {
            $res = $this->k_stages($request['out_trans_no'], $request['pay_amount'],$alipay_fund_order_no);

            if ($res) {
                $log['keyword'] = '订单扣款成功';
            }
        }

        //取消订单后异步通知

        if ($request['notify_type'] == 'ZM_RENT_ORDER_CANCEL') {
            $res = $this->zmOrder_cancel($request);

            if ($res) $log['keyword'] = '订单取消成功';
        }

        if ($res) {
            M('log_xcx')->add($log);
            echo "success";
            exit;
        } else {
            $log['keyword'] = '失败';
            M('log_xcx')->add($log);
            echo "fail";
        }

    }


    /**
     *  订单创建成功后异步通知地址
     *  小程序接口 my.zmRentTransition (Object)创建订单成功后发送给商户的异步通知
     */
    private function createOrder_notify($arr)
    {
        //商户订单号
        $order_id = $arr['out_order_no'];
        $zm_order_no = $arr['zm_order_no'];

        $orders_row = M('orders')->where("order_id='$order_id'")->field("my_cou_id,order_status,user_phone,goods_id")->find();

        if ($orders_row['order_status'] == 0) {
            if ($orders_row['my_cou_id']) {
                $time = date("Y-m-d H:i:s", time());

                //修改我的优惠券表 使用状态 使用时间
                M("cou_coupon")->where("id='$orders_row[my_cou_id]'")->save(array("my_cou_status" => 2, "use_time" => $time));

            }

            $res = M('orders')->where("order_id='$order_id' ")->save(array('order_status' => 2, 'zm_order_no' => $zm_order_no));

            //商品浏览量统计
            goods_statia($orders_row["goods_id"], $orders_row["user_phone"], 2);

            if (!$res) return false;
        }

        return true;
    }


    /**
     *  小程序订单取消
     *
     */
    private function zmOrder_cancel($arr)
    {
        //商户订单号
        $order_id = $arr['out_order_no'];     //I('out_order_no');
        $zm_order_no = $arr['zm_order_no'];   //芝麻单号

        $res = M('orders')->where("order_id='$order_id' ")->save(array('describe' => ''));

        if ($res === false) {
            return false;
        }

        return true;
    }


    /**
     *  扣款(含分期扣款)
     * @param out_trans_no   商户传入的资金交易号(账单分期表ID)
     * @param pay_amount     金额
     * $alipay_fund_order_no 资金流水号，用于商户与支付宝进行对账
     */
    private function k_stages($out_trans_no, $pay_amount,$alipay_fund_order_no='')
    {
        $res = save_order_stages($out_trans_no, $pay_amount,$alipay_fund_order_no);
        $data = ['dk_status' => 2];
        if(!empty($alipay_fund_order_no)){
            $data['alipay_fund_order_no'] = $alipay_fund_order_no;
        }
        M('pay_dk_bill')->where("stages_id='$out_trans_no'")->save($data);

        return $res;
    }

}